import React, { useState } from 'react';
import { View, Input, Button, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import './register.module.scss';
import { showToast } from '@tarojs/taro';
import axios from 'axios';

const Register: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const handleRegister = async () => {
    if (!username || !password || !confirmPassword) {
      showToast({ title: '请填写所有字段', icon: 'none' });
      return;
    }
    if (password !== confirmPassword) {
      showToast({ title: '两次输入的密码不一致', icon: 'none' });
      return;
    }

    try {
      const response = await axios.post('http://localhost:3000/jjk/register', { username, password });
      if (response.status === 200) {
        showToast({ title: '注册成功', icon: 'success' });
        Taro.navigateTo({ url: '/pages/login/login' });
      } else {
        showToast({ title: response.data.message || '注册失败', icon: 'none' });
      }
    } catch (error) {
      showToast({ title: '网络错误，请稍后再试', icon: 'none' });
    }
  };



  const goBack = () => {
    Taro.navigateTo({ url: '/pages/login/login' });
  };

  return (
    <View className="register-container">
      <View className="login-box">
        <Text className="back-button" onClick={goBack}>返回</Text>
        <Text className="register-title">注册</Text>
        <View className="form-item">
          <Input
            className="input"
            placeholder="请输入用户名"
            value={username}
            onInput={(e) => setUsername(e.detail.value)}
          />
        </View>
        <View className="form-item">
          <Input
            className="input"
            type="password"
            placeholder="请输入密码"
            value={password}
            onInput={(e) => setPassword(e.detail.value)}
          />
        </View>
        <View className="form-item">
          <Input
            className="input"
            type="password"
            placeholder="请确认密码"
            value={confirmPassword}
            onInput={(e) => setConfirmPassword(e.detail.value)}
          />
        </View>
        <Button className="register-button" onClick={handleRegister}>注册</Button>
      </View>
    </View>
  );
};

export default Register;